package com.ncmmall.api.apis.mall;


import com.ncmmall.api.apis.service.Result;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.merchant.banner.MerchantBanner;
import com.ncmmall.domain.business.merchant.banner.QMerchantBanner;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author linxs
 * 门店
 */
@RestController
@RequestMapping(value = "/shop")
@Slf4j
public class ShopApi {


    @Autowired
    private QueryChannelService queryChannelService;

    @Value("${store.domain}")
    private String storeDomain;

    /**
     * 店铺信息
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public Result info(long id) {
        Result result = new Result();
        try {

            WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(id).and(QWebUser.webUser.role.name.eq("MERCHANT")), WebUser.class);

            Map<String, Object> data = Maps.newHashMap();
            data.put("name", merchant.getShopName());
            data.put("shopBanner", storeDomain + "/uploads/" + merchant.getShopBanner());
            data.put("logo", storeDomain + "/avatar/" + merchant.getAvatar());
            data.put("telephone", merchant.getMobile());
            data.put("banners", queryChannelService.findAll(QMerchantBanner.merchantBanner.merchant.id.eq(merchant.getId()).and(QMerchantBanner.merchantBanner.status.eq(2)), MerchantBanner.class)
                    .stream()
                    .peek(input -> input.setImage(storeDomain + "/uploads/" + input.getImage()))
                    .collect(Collectors.toList())
            );

            data.put("channels", queryChannelService.selectAllMap("select * from mall_goods_channel where deleteStatus = 0 and status = 1 and id in (select channel_id from mall_merchant_goods_channel where merchant_id = :id)", ImmutableMap.of("id", merchant.getId())));

            return result.ok().inject(data);

        } catch (IllegalArgumentException e) {

            return result.fail().setMsg(e.getMessage());

        } catch (Exception e) {

            log.error("[获取商品详情异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }


    /**
     * 店铺商品
     */
    @RequestMapping(value = "/goodsList", method = RequestMethod.GET)
    @ResponseBody
    public Result goodsList(@RequestParam(defaultValue = "0") long shopId, @RequestParam(defaultValue = "0") int orderType, @RequestParam(defaultValue = "0") int orderMethod, @RequestParam(defaultValue = "0") long channelId, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "20") int pageSize) {
        Result result = new Result();
        try {

            QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);

            String hql = "select g from Goods g where g.status = 3 and g.merchant.id = :id ";
            Map<String, Object> map = new HashMap<>();
            map.put("id", shopId);

            hql = builderSQL(orderType, orderMethod, channelId, map, hql);

            QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(map), Goods.class);
            for (Goods goods : page.getResult()) {
                goods.setDefaultImage(storeDomain + "/uploads/" + goods.getDefaultImage());
            }

            return result.ok().inject(page);

        } catch (Exception e) {

            log.error("[分类商品列表获取数据异常]", e);
            return result.fail().setMsg("网络连接失败");
        }

    }

    private String builderSQL(int orderType, int orderMethod, long channelId, Map<String, Object> map, String hql) {

        if (channelId > 0) {
            hql += " and g.goodsChannel.parent.parent.id = :cid ";
            map.put("cid", channelId);
        }

        //按价格排序
        if (orderType == 1) {

            if (orderMethod == 0) {
                hql += " order by g.defaultPrice ";
            }
            if (orderMethod == 1) {
                hql += " order by g.defaultPrice desc ";
            }
            if (orderMethod == 2) {
                hql += " order by g.defaultPrice asc ";
            }

        }

        if (orderType == 2) {

            if (orderMethod == 0) {
                hql += " order by g.salesVolume ";
            }
            if (orderMethod == 1) {
                hql += " order by g.salesVolume desc ";
            }
            if (orderMethod == 2) {
                hql += " order by g.salesVolume asc ";
            }

        }


        return hql;
    }


}
